#import "CalcController.h"

@implementation CalcController




- (void)textDidEndEditing:(NSNotification *)aNotification
{
  

  
  NSMutableString *str = [NSMutableString stringWithString:[inputField stringValue]];
 
  NSArray *arguments = nil;
  

  

  
  
  NSMutableString *argstring = [NSMutableString stringWithString:@"/usr/bin/gcalc"];
  [argstring appendString:@","];
  [argstring appendString:str];
  
  
  arguments = [argstring componentsSeparatedByString:@","];
  //append filename
  
  [self setShellWrapper:[[AMShellWrapper alloc] initWithController:self inputPipe:nil outputPipe:nil errorPipe:nil workingDirectory:@"." environment:nil arguments:arguments]];
  
  NS_DURING
	if (shellWrapper) {
	  [shellWrapper setOutputStringEncoding:NSASCIIStringEncoding];
	  [shellWrapper startProcess];
	} else {
	  //Something wrong.
	}
	NS_HANDLER
	  NSLog(@"Caught %@: %@", [localException name], [localException reason]);
	  [self processLaunchException:localException];
	NS_ENDHANDLER

	
}

- (void)setShellWrapper:(AMShellWrapper *)newShellWrapper
{
  id old = nil;
  
  if (newShellWrapper != shellWrapper) {
	old = shellWrapper;
	shellWrapper = [newShellWrapper retain];
	[old release];
  }
}








- (void)appendOutput:(NSString *)output
{
  NSMutableString *bufferval = [NSMutableString stringWithString:[resultField string]];
  [bufferval appendString:output];
  [resultField setString:bufferval];
  
}


-(void) awakeFromNib
{
   
  [inputField setDelegate:self];
  NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  [nc addObserver:self
		 selector:@selector(textDidEndEditing:)
			 name:@"NSControlTextDidEndEditingNotification"
		   object:inputField];
  NSLog(@"registered");
}


// output from stderr
- (void)appendError:(NSString *)error
{
  
  NSMutableString *bufferval = [NSMutableString stringWithString:[resultField string]];
  [bufferval appendString:error];
  [resultField setString:bufferval];
}

- (AMShellWrapper *)shellWrapper
{
  return shellWrapper;
}




- (void)dealloc
{
  [shellWrapper release];
  [super dealloc];
}

- (IBAction)stopTask:(id)sender
{
  [shellWrapper stopProcess];
}

// This method is a callback which your controller can use to do other initialization
// when a process is launched.
- (void)processStarted:(id)sender
{
  [progressIndicator startAnimation:self];

}

// This method is a callback which your controller can use to do other cleanup
// when a process is halted.
- (void)processFinished:(id)sender withTerminationStatus:(int)resultCode
{
  [progressIndicator stopAnimation:self];
  [self setShellWrapper:nil];
  if(resultCode == 0)
  {
   
	
  }
  else
  {
	NSLog(@"Something went wrong, GRR!!!");
  }
  [sender release];

}

- (void)processLaunchException:(NSException *)exception
{
  
  [progressIndicator stopAnimation:self];
  [self setShellWrapper:nil];
}


@end
